package cn.itcast.controller.system;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.system.Module;
import cn.itcast.service.system.ModuleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("system/module")
public class ModuleController extends BaseController {

    @Autowired
    private ModuleService moduleService;


    //进入菜单管理页面
    @RequestMapping(value = "/list", name = "进入菜单管理页面")
    public String findAll(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Module> pageInfo = moduleService.findPage(page, pageSize);
        request.setAttribute("page", pageInfo);
        return "system/module/module-list";
    }

    //进入新增菜单页面
    @RequestMapping(value = "/toAdd", name = "进入新增菜单页面")
    public String toAdd() {
        //查询所有本菜单所有数据
        List<Module> moduleList = moduleService.findAll();
        request.setAttribute("menus",moduleList);
        return "system/module/module-add";
    }

    //保存菜单
    @RequestMapping(value = "/edit", name = "保存菜单")
    public String edit(Module module) {
        //id为空是新增,反之是修改
        if (StringUtils.isEmpty(module.getId())) {
            //设置id
            module.setId(UUID.randomUUID().toString());
            //保存
            moduleService.save(module);
        } else {
            //修改
            moduleService.update(module);
        }
        //重定向到列表数据
        return "redirect:/system/module/list.do";
    }

    //进入修改菜单页面
    @RequestMapping(value = "/toUpdate",name = "进入修改菜单页面")
    public String toUpdate(String id){
        //根据id查询
        Module module = moduleService.findById(id);
        //放入request域中
        request.setAttribute("module",module);

        List<Module> moduleList = moduleService.findAll();
        request.setAttribute("menus",moduleList);
        //修改页面和新增页面公用一套
        return "system/module/module-add";
    }

    //删除菜单
    @RequestMapping(value = "/delete",name = "删除菜单")
    public String delete(String id){
        moduleService.deleteById(id);
        return "redirect:/system/module/list.do";
    }
}
